'use strict';
const uniID = require('uni-id-common')
const ASE= require('ase')
exports.main = async (event, context) => {
	if(event.uniIdToken==null){
		return []
	}
	const uniIDIns = uniID.createInstance({
	    context: context,
	  })
 const res=await uniIDIns.checkToken(event.uniIdToken)
   const db = uniCloud.databaseForJQL({
   		event,
   		context 
   	});
	db.setUser({
		role: ['admin']
	})
	event=JSON.parse(ASE.AES.decrypt(event.data,'yclycl1314520520','9740022097400220'))
	if(event.type=='send'){
		var from=event.form.type==1?'6423ca1309e298816037d709':res.uid
		event.form.from=res.uid
		event.form.time=new Date()
		await db.collection("message").add(event.form)
		return {msg:"回复成功"}
	}else if(event.type=='receive'){
		const msg=await db.collection("message").where({_id:event.form.id}).get()
		if(msg.data[0].en_mode){
			return {msg:"不可重复领取",mode:false}
		}
		const userinfo=await db.collection("uni-id-users").where({_id:res.uid}).get()
		if(msg.data[0].en_type=='limit'){
			await db.collection("uni-id-users").where({
				_id: res.uid
			}).update({
				limit: userinfo.data[0].limit+msg.data[0].en_value*1024*1024*1024
			})
			await db.collection("bill").add({
				time: new Date,
				title: "附件领取",
				content: msg.data[0].en_value + "GB",
				user_id: res.uid,
				type: "+"
			})
		}else{
			var vipday;
			if(userinfo.data[0].vip==0||new Date().getTime()>userinfo.data[0].vip){
				vipday=new Date().getTime()+msg.data[0].en_value*86400000;
			}else{
				vipday=userinfo.data[0].vip+msg.data[0].en_value*86400000;
			}
			await db.collection("uni-id-users").where({
				_id: res.uid
			}).update({
				vip: vipday
			})
		}
		await db.collection("message").where({_id:event.form.id}).update({en_mode:true})
		return {msg:"领取成功"}
	}
};
